package com.thinkersre.controller;


import com.thinkersre.entity.*;
import com.thinkersre.event.EventProducer;
import com.thinkersre.service.CommentService;
import com.thinkersre.service.DiscussPostService;
import com.thinkersre.service.LikeService;
import com.thinkersre.service.UserService;
import com.thinkersre.util.HostHolder;
import com.thinkersre.util.RedisKeyUtil;
import com.thinkersre.util.ThinkersReConstant;
import com.thinkersre.util.ThinkersReUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements ThinkersReConstant {
    @Resource
    private DiscussPostService discussPostService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private UserService userService;
    @Resource
    private CommentService commentService;
    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;
    @Resource
    private RedisTemplate redisTemplate;
    @PostMapping("/add")
    @ResponseBody
    public String addDiscussPost(String title, String content){
        User user = hostHolder.getUser();
        if(user == null){
            return ThinkersReUtil.getJSONString(403,"你还没有登录，没有权限");
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());

        eventProducer.fireEvent(event);

        //计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,discussPost.getId());



        //报错的情况之后统一处理
        return ThinkersReUtil.getJSONString(0,"发布成功");

    }
    @GetMapping("/detail/{discussPostId}")
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page){
        //帖子
        DiscussPost post = discussPostService.findDiscusPostById(discussPostId);
        model.addAttribute("post",post);
        //作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user",user);
        //点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,discussPostId);
        model.addAttribute("likeCount",likeCount);
        //点赞动态
        int likeStatus = hostHolder.getUser()==null?0:likeService.findEntityLikeStatus(hostHolder.getUser().getId(),ENTITY_TYPE_POST,discussPostId);
        model.addAttribute("likeStatus",likeStatus);
        //评论分条信息
        page.setPageSize(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRowsTotal(post.getCommentCount());

        //评论：给帖子的回复
        //回复：给回复的回复
        //评论列表
        List<Comment> commentList = commentService.findCommentsByEntity(ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getPageSize());
        //评论map列表
        List<Map<String,Object>> commentmapList = new ArrayList<>();
        if (commentList != null){
                for (Comment comment : commentList){
                    //评论map
                    Map<String,Object> commentmap = new HashMap<>();
                    //评论
                    commentmap.put("comment",comment);
                    //作者
                    commentmap.put("user",userService.findUserById(comment.getUserId()));


                    //点赞数量
                    likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                    commentmap.put("likeCount",likeCount);
                    //点赞动态
                    likeStatus = hostHolder.getUser()==null?0:likeService
                            .findEntityLikeStatus(hostHolder.getUser().getId(),ENTITY_TYPE_COMMENT,comment.getId());
                    commentmap.put("likeStatus",likeStatus);

                    //回复列表
                    List<Comment> replyList = commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                    //回复map列表
                    List<Map<String,Object>> replymapList = new ArrayList<>();
                    if (replyList != null){
                        for (Comment reply : replyList){
                            Map<String ,Object> replymap = new HashMap<>();
                            //回复
                            replymap.put("reply",reply);
                            //作者
                            replymap.put("user",userService.findUserById(reply.getUserId()));

                            //点赞数量
                            likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                            replymap.put("likeCount",likeCount);
                            //点赞动态
                            likeStatus = hostHolder.getUser()==null?0:likeService
                                    .findEntityLikeStatus(hostHolder.getUser().getId(),ENTITY_TYPE_COMMENT,reply.getId());
                            replymap.put("likeStatus",likeStatus);

                            //回复目标
                            User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                            replymap.put("target",target);

                            replymapList.add(replymap);
                        }
                    }
                    commentmap.put("replys",replymapList);
                    //回复数量
                    int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                    commentmap.put("replyCount",replyCount);
                    commentmapList.add(commentmap);

                }
        }
        model.addAttribute("comments",commentmapList);
        return "/site/discuss-detail";
    }


    // 置顶
    @PostMapping("/top")
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(id,1);


        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);

        eventProducer.fireEvent(event);


        return ThinkersReUtil.getJSONString(0);
    }

    //加精
    @PostMapping("/wonderful")
    @ResponseBody
    public String setWonderful(int id){
        discussPostService.updateStatus(id,1);


        //触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);

        eventProducer.fireEvent(event);

        //计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,id);



        return ThinkersReUtil.getJSONString(0);
    }
    //删除
    @PostMapping("/delete")
    @ResponseBody
    public String setDelete(int id){
        discussPostService.updateStatus(id,2);

        //触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);

        eventProducer.fireEvent(event);


        return ThinkersReUtil.getJSONString(0);
    }




}
